package com.longxi.tianjintianbao.ui.presenter.visitor;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.visitor.CertificateType;
import com.longxi.tianjintianbao.model.visitor.Visitor;
import com.longxi.tianjintianbao.ui.activity.repair_publish.SelectAreaActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.presenter.repair_publish.SelectAreaAtPresenter;
import com.longxi.tianjintianbao.ui.view.visitor.ISignVisitorAtView;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SignVisitorAtPresenter extends BasePresenter<ISignVisitorAtView> {

    private String build = "";
    private String buildid = "";
    private Visitor visitor;
    public String comevisitortype = "住户";

    public SignVisitorAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
        visitor = (Visitor) intent.getSerializableExtra(AppConst.VISITOR);
        mContext.setTitle("访客登记");
        mContext.setTvLeft(MyUtils.getString(R.string.back));

        if(visitor == null){
            return;
        }
        mContext.setTitle("访客详情");
        if("".equals(visitor.getVisitdate())){
            getView().getBtnLogin().setText("访客离开登记");
        }else{
            getView().getBtnLogin().setVisibility(View.GONE);
        }
        setDetail();
    }

    private void setDetail() {
        getView().getEtVisitorName().setText(visitor.getVisitorname());
        getView().getEtVisitorPhone().setText(visitor.getVisitorphone());
        getView().getEtCause().setText(visitor.getCause());
        getView().getTvHouse().setText(visitor.getBuild());
        getView().getEtMaster().setText(visitor.getMaster());
        getView().getEtMasterPhone().setText(visitor.getMasterphone());
        getView().getEtRemarks().setText(visitor.getRemarks());

        getView().getEtVisitorName().setFocusable(false);
        getView().getEtVisitorPhone().setFocusable(false);
        getView().getEtCause().setFocusable(false);
        getView().getTvHouse().setEnabled(false);
        getView().getEtMaster().setFocusable(false);
        getView().getEtMasterPhone().setFocusable(false);
        getView().getEtRemarks().setFocusable(false);

        if(!"".equals(visitor.getVisitdate())){
            getView().getTvLeavedateTip().setVisibility(View.VISIBLE);
            getView().getLlLeavedate().setVisibility(View.VISIBLE);
            getView().getTvLeavedate().setText(visitor.getVisitdate());
        }
    }

    public void btnLogin(){
        if(visitor == null){
            saveVisitor();
        }else{
            saveVisitorLeave();
        }
    }

    private void saveVisitorLeave() {
        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billid", visitor.getBillid());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveVisitorLeave(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("提交成功");
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    public void saveVisitor() {
        long userid = MyApplication.loginUser.userid;
        String visitorname = getEditText(getView().getEtVisitorName());
        String visitorphone = getEditText(getView().getEtVisitorPhone());
        String receivedate = getView().getTvReceivedate().getText().toString();
        String cause = getEditText(getView().getEtCause());
        String master = getEditText(getView().getEtMaster());
        String masterphone = getEditText(getView().getEtMasterPhone());
        String housedept = getEditText(getView().getEtHousedept());
        String remarks = getEditText(getView().getEtRemarks());
        String visitdate = "";

        if(TextUtils.isEmpty(buildid)){
            MyUtils.showToast("请选择所属项目");
            return;
        }

        if(TextUtils.isEmpty(receivedate)){
            MyUtils.showToast("请选择预约来访时间");
            return;
        }

        if("".equals(visitorname) || visitorname == null){
            MyUtils.showToast(getView().getEtVisitorName().getHint().toString());
            return;
        }

        if("".equals(visitorphone) || visitorphone == null){
            MyUtils.showToast(getView().getEtVisitorPhone().getHint().toString());
            return;
        }

        if(TextUtils.isEmpty(cause)){
            MyUtils.showToast("来访事由");
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", "");
            object.put("userid", userid);
            object.put("build", build);
            object.put("buildid", buildid);
            object.put("visitorname", visitorname);
            object.put("visitorphone", visitorphone);
            object.put("receivedate", receivedate);
            object.put("visitortype", comevisitortype);
            object.put("master", master);
            object.put("masterphone", masterphone);
            object.put("housedept", housedept);
            object.put("cause", cause);
            object.put("visitdate", visitdate);
            object.put("remarks", remarks);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveVisitor(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("提交成功");
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    /**
     * 选择小区地址
     */
    public void selectArea() {
        Intent mainIntent = new Intent(mContext, SelectAreaActivity.class);
        mainIntent.putExtra(SelectAreaAtPresenter.REPAIRAREA,"1");
        mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_REPAIR_CONTENT);
    }

    public String getEditText(EditText editText){
        return editText.getText().toString().trim();
    }

    /**
     * 获取证件类型
     */
    public void getCertificatetype(){
        mContext.showWaitingDialog(MyUtils.getString(R.string.load));

        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.getUserid());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().getCertificatetype(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<CertificateType>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<CertificateType> result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }


            }
        });
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AppConst.IntentRequstCode.ACTIVITY_REPAIR_CONTENT) {
            if(data != null){
                build = data.getStringExtra("area");
                buildid = data.getStringExtra("buildId");
                getView().getTvHouse().setText(build);
                getView().getEtMaster().setText(data.getStringExtra("custname"));
                getView().getEtMasterPhone().setText(data.getStringExtra("custphone"));
            }
        }
    }
}
